package com.enzoism.springboot.dive.lambda;

import com.enzoism.springboot.dive.model.UsrModel;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 1）List转Map
 * 2）List中对象的属性转为Map
 * 3）List分组
 * 4）List条件过滤
 */
@Slf4j
public class A01List2Map {
    public static void main(String[] args) {
        List<UsrModel> usrList = UsrModel.initList();
        // 场景一：进行list转map
        收集对象本身转为Map(usrList);
        收集对象属性转为Map(usrList);

        // 场景二：进行list分组
        根据对象的属性进行分组(usrList);

        // 场景三：
        使用Lambda进行条件过滤(usrList);
    }

    public static void 收集对象本身转为Map(List<UsrModel> usrList) {
        // 方式一： item -> item
        Map<String, UsrModel> collect1 = usrList.stream().collect(Collectors.toMap(UsrModel::getUsrId, item -> item));
        log.info(collect1.toString());

        // 方式二： Function.identity()
        Map<String, UsrModel> collect2 = usrList.stream().collect(Collectors.toMap(UsrModel::getUsrId, Function.identity()));
        log.info(collect2.toString());

        // 方式三： 可能遇到重复key值
        Map<String, UsrModel> collect3 = usrList.stream().collect(Collectors.toMap(UsrModel::getUsrId, Function.identity(), (key1, key2) -> key2));
        log.info(collect3.toString());

        // 方式四： 可能遇到重复key值-并指定接收的Map
        Map<String, UsrModel> collect4 = usrList.stream().collect(Collectors.toMap(UsrModel::getUsrId, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
        log.info(collect4.toString());
    }

    public static void 收集对象属性转为Map(List<UsrModel> usrList) {
        Map<String, Long> collect = usrList.stream().collect(Collectors.toMap(UsrModel::getUsrId, UsrModel::getUsrNum));
        log.info(collect.toString());
    }

    public static void 根据对象的属性进行分组(List<UsrModel> usrList) {
        Map<String, List<UsrModel>> collect = usrList.stream().collect(Collectors.groupingBy(UsrModel::getUsrId));
        log.info(collect.toString());
    }

    public static void 使用Lambda进行条件过滤(List<UsrModel> usrList){
        List<UsrModel> list = usrList.stream()
                .filter(u -> u.getClkNum() >= 15 && u.getUsrNum() <= 2)
                .collect(Collectors.toList());
        log.info(list.toString());
    }

}
